package show.me.the.money.config.schema;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
@SuppressWarnings("unchecked")
public class SchemaRelation {
	private String type;
	private String entryName;
	private String fullName;
	private String alias;
	private List<Properties> updates = new ArrayList<Properties>();
	private List<Properties> joins = new ArrayList<Properties>();
	private List joinCnds;
	
	public SchemaRelation(String type,String entryName,String alias){
		this.type = type;
		this.entryName = entryName;
		this.alias = alias;
		fullName = SchemaController.instance().getSchema(entryName).getTableName() + " " + alias;
	}
	
	public String getType(){
		return type;
	}
	
	public String getEntryName(){
		return entryName;
	}
	
	public String getAlias(){
		return alias;
	}
	
	public String getFullEntryName(){
		return fullName;
	}
	
	public Schema getEntrySchema(){
		return SchemaController.instance().getSchema(entryName);
	}
	
	public void addUpdate(String from,String to,String func){
		Properties p = new Properties();
		p.setProperty("from", from);
		p.setProperty("to", to);
		p.setProperty("func", func);
		updates.add(p);
	}
	
	public void addJoinCondition(String parent,String child){
		Properties p = new Properties();
		p.setProperty("parent", parent);
		p.setProperty("child", child);
		joins.add(p);
	}
	
	public List getJoinCondition(){
		if(joinCnds != null){
			return joinCnds;
		}
		String pAlias = "";
		String cAlias = "";
		if(type.equals("parent")){
			pAlias = alias;
			cAlias = "a";
		}
		else{
			pAlias = "a";
			cAlias = alias;
		}
		int size = joins.size();
		if(size > 0){
			List cnds = new ArrayList();
			for(Properties p : joins){
				List cnd = new ArrayList();
				String f1 = pAlias + "." + p.getProperty("parent");
				String f2 = cAlias + "." + p.getProperty("child");
							
				cnd.add("eq");
				
				List ref1 = new ArrayList();
				ref1.add("$");
				ref1.add(f1);
				
				List ref2 = new ArrayList();
				ref2.add("$");
				ref2.add(f2);
				
				cnd.add(ref1);
				cnd.add(ref2);
				cnds.add(cnd);
			}
			if(size == 1){
				joinCnds = (List)cnds.get(0);
			}
			else{
				joinCnds = cnds;
			}
		}
		return joinCnds;
	}
	
	public List<Properties>getUpdates(){
		return updates;
	}
	
	public List<Properties>getJoinConditions(){
		return joins;
	}	
}
